package cn.ibdsr.human.service.impl;

import cn.ibdsr.human.constant.*;
import cn.ibdsr.human.db.mapper.ServerInitMapper;
import cn.ibdsr.human.db.mapper.UserDetailMapper;
import cn.ibdsr.human.db.mapper.UserMapper;
import cn.ibdsr.human.db.model.Education;
import cn.ibdsr.human.db.model.ServerInit;
import cn.ibdsr.human.db.model.User;
import cn.ibdsr.human.db.model.UserDetail;
import cn.ibdsr.human.exception.BizExceptionEnum;
import cn.ibdsr.human.exception.BusinessException;
import cn.ibdsr.human.service.UserDetailService;
import cn.ibdsr.human.transfer.JobStatusDTO;
import cn.ibdsr.human.transfer.ServerInitDTO;
import cn.ibdsr.human.transfer.UserDetailDTO;
import cn.ibdsr.human.transfer.UserDetailSaveDTO;
import cn.ibdsr.human.transfer.job.JobListResponseDTO;
import cn.ibdsr.human.transfer.job.JobResponseDTO;
import cn.ibdsr.human.transfer.platform.PlatformUserDetialDTO;
import cn.ibdsr.human.transfer.platform.UserListDetailDTO;
import cn.ibdsr.human.transfer.platform.UserListResponseDTO;
import cn.ibdsr.human.transfer.platform.UserQueryDTO;
import cn.ibdsr.human.util.MybatisPlusPage;
import cn.ibdsr.human.warpper.JobResponseWarpper;
import cn.ibdsr.human.warpper.UserDetailWarpper;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;

/**
 * @description:
 * @author: cdl
 * @email: iamcimon@qq.com
 * @date: 2021/8/3 13:56
 */
@Service
@Slf4j
public class UserDetailServiceImpl implements UserDetailService {
    @Resource
    private UserMapper userMapper;
    @Resource
    private UserDetailMapper userDetailMapper;

    @Resource
    private ServerInitMapper serverInitMapper;

    /**
     * 根据id获取用户信息
     *
     * @param userId
     * @return
     */
    @Override
    public UserDetailDTO getUserDetail(Long userId) {

        UserDetailDTO userDetailDTO = new UserDetailDTO();
        User user = userMapper.selectById(userId);
        if (user == null) {
            throw new BusinessException(BizExceptionEnum.USER_NOT_EXISTED);
        }
        userDetailDTO.setPhone(user.getAccount());
        UserDetail userDetail = null;
        if (user.getCompanyId() == null) {
            return userDetailDTO;

        } else {
            userDetail = userDetailMapper.selectById(user.getCompanyId());
            if (userDetail == null) {
                return userDetailDTO;
            }
            JSONObject jsonObject = (JSONObject) (new UserDetailWarpper(  JSONObject.parseObject(JSONObject.toJSONString(userDetail)) ,true)).warp();
            userDetailDTO = JSONObject.parseObject(JSONObject.toJSONString(jsonObject), UserDetailDTO.class);
            userDetailDTO.setPhone(user.getAccount());
        }
        userDetailDTO.setJobStatusDes(JobStatusEnum.valueOf(userDetail.getJobStatus()).getDesc());
        return userDetailDTO;
    }

    /**
     * 保存个人信息
     *
     * @param userId
     * @param userDetailSaveDTO
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public Long save(Long userId, UserDetailSaveDTO userDetailSaveDTO) {
        User user = userMapper.selectById(userId);
        if (user == null || !user.getSysType().equals(PlatformEnum.USER.getCode())) {
            throw new BusinessException(BizExceptionEnum.USER_NOT_EXISTED);
        }
        UserDetail userDetail = null;
        if (user.getCompanyId() == null) {
            return createuser(user,userDetailSaveDTO);
        } else {
            userDetail = userDetailMapper.selectById(user.getCompanyId());
            if(userDetail==null){
              return createuser(user,userDetailSaveDTO);
            }
            UserDetail userDetailTemp = new UserDetail();
            userDetailTemp = JSONObject.parseObject(JSONObject.toJSONString(userDetailSaveDTO), UserDetail.class);
            userDetailTemp.setId(userDetail.getId());
            userDetailTemp.updateById();
            return userDetailTemp.getId();
        }

    }
    private Long createuser(User user, UserDetailSaveDTO userDetailSaveDTO){
        UserDetail  userDetail = new UserDetail();
        userDetail = JSONObject.parseObject(JSONObject.toJSONString(userDetailSaveDTO), UserDetail.class);
        userDetailMapper.insert(userDetail);
        user.setCompanyId(userDetail.getId());
        user.setUpdateTime(LocalDateTime.now());
        userMapper.updateById(user);
        return  userDetail.getId();
    }

    /**
     * 修改工作状态
     * @param userId
     * @param jobStatusDTO
     * @return
     */
    @Override
    public Long saveJobStatus(Long userId, JobStatusDTO jobStatusDTO) {
        User user = userMapper.selectById(userId);
        if (user == null || !user.getSysType().equals(PlatformEnum.USER.getCode())) {
            throw new BusinessException(BizExceptionEnum.USER_NOT_EXISTED);
        }
        UserDetail userDetail = userDetailMapper.selectById(user.getCompanyId());
        if (userDetail == null) {
            throw new BusinessException(BizExceptionEnum.USER_NOT_EXISTED);
        }
        if(!userDetail.getJobStatus().equals(jobStatusDTO.getJobStatus())){
            userDetail.setJobStatus(jobStatusDTO.getJobStatus());
            userDetail.setUpdateTime(LocalDateTime.now());
            userDetail.updateById();
            return userDetail.getId();
        }
        return userDetail.getId();
    }

    /**
     * 获取简历填写进度
     * @param userId
     * @return
     */
    @Override
    public ServerInitDTO getProgresses(Long userId) {

        ServerInitDTO serverInitDTO=new ServerInitDTO();
        User user = userMapper.selectById(userId);
        if (user == null || !user.getSysType().equals(PlatformEnum.USER.getCode())) {
            throw new BusinessException(BizExceptionEnum.USER_NOT_EXISTED);
        }
        QueryWrapper<ServerInit> serverInitQueryWrapper=new QueryWrapper<>();
        serverInitQueryWrapper.eq("type", ServerInitEnum.SERVER_PHONE.getType());
        ServerInit serverInit=serverInitMapper.selectOne(serverInitQueryWrapper);
        if(serverInit==null){
            throw new BusinessException(BizExceptionEnum.SERVIER_INIT_ERROR);
        }
        serverInitDTO.setTelePhone(serverInit.getConfigValue());
        Integer total=13;
        UserDetail userDetail = userDetailMapper.selectById(user.getCompanyId());
        Integer currentValue=1;
        if (userDetail == null) {
            BigDecimal bigDecimal=new BigDecimal(currentValue*1.0/total*100);
            BigDecimal setScale = bigDecimal.setScale(2,BigDecimal.ROUND_HALF_DOWN);
            serverInitDTO.setProgress( setScale.longValue()+"%");
        }else {
            //phone 1
            if(StringUtils.isNotEmpty(userDetail.getName())){
                currentValue++;//2
            }
            if(StringUtils.isNotEmpty(userDetail.getIdCardNo())){
                currentValue++;//3
            }
            if(userDetail.getAge()!=null){
                currentValue++;//4
            }
            if(userDetail.getGender()!=null){
                currentValue++;//5
            }
            if(StringUtils.isNotEmpty(userDetail.getMajor())){
                currentValue++;//6
            }
            if(userDetail.getExperience()!=null){
                currentValue++;//7
            }
            if(StringUtils.isNotEmpty(userDetail.getSalary())){
                currentValue++;//8
            }
            if(StringUtils.isNotEmpty(userDetail.getJobRequire())){
                currentValue++;//9
            }
            if(userDetail.getEducation()!=null){
                currentValue++;//10
            }
            if(userDetail.getPolitic()!=null){
                currentValue++;//11
            }
            if(userDetail.getMarried()!=null){
                currentValue++;//12
            }
            if(StringUtils.isNotEmpty(userDetail.getAddress())){
                currentValue++;//13
            }
            BigDecimal bigDecimal=new BigDecimal(currentValue*1.0/total*100);
            BigDecimal setScale = bigDecimal.setScale(2,BigDecimal.ROUND_HALF_DOWN);
            serverInitDTO.setProgress( setScale.longValue()+"%");

        }
        return serverInitDTO;
    }

    /**
     * 查询用户信息
     * @param userQueryDTO
     * @return
     */
    @Override
    public UserListResponseDTO getUserList(UserQueryDTO userQueryDTO) {
        if (userQueryDTO.getPageNo() == null || userQueryDTO.getPageNo() <= 0) {
            userQueryDTO.setPageNo(1L);
        }
        if (userQueryDTO.getPageSize() == null || userQueryDTO.getPageSize() <= 0) {
            userQueryDTO.setPageSize(BizConstants.DEFAULT_PAGE_SIZE);
        } else if (userQueryDTO.getPageSize() > BizConstants.MAX_PAGE_SIZE) {
            throw new BusinessException(BizExceptionEnum.REQUEST_ERROR);
        }
        Page<UserListDetailDTO> page = MybatisPlusPage.defaultNewPage(userQueryDTO);
        List<UserListDetailDTO> users = userMapper.listByPage(page,
                userQueryDTO.getName(),
                userQueryDTO.getPhone(),
                userQueryDTO.getMajor(),
                userQueryDTO.getJobStatus(),
                userQueryDTO.getGender(),
                userQueryDTO.getExperience(),
                userQueryDTO.getMinAge(),
                userQueryDTO.getMaxAge()
        );
        // 创建返回结果
        List<UserListDetailDTO> usersNew=new ArrayList<>();
        Long pageIdex = page.getSize() * (page.getCurrent() - 1);
        for (UserListDetailDTO user : users) {
            pageIdex++;
            JSONObject jsonObject = (JSONObject) (new UserDetailWarpper(JSONObject.parseObject(JSONObject.toJSONString(user)),true)).warp();
            user = JSONObject.parseObject(JSONObject.toJSONString(jsonObject), UserListDetailDTO.class);
            if(user.getJobStatus()!=null){
                user.setJobStatusDes(JobStatusEnum.valueOf(user.getJobStatus().intValue()).getDesc());
            }
            user.setRank(pageIdex);
            usersNew.add(user);
        }
        page.setRecords(usersNew);
        UserListResponseDTO userListResponseDTO = new UserListResponseDTO();
        userListResponseDTO.setPageNo(page.getCurrent());
        userListResponseDTO.setPageSize(page.getSize());
        userListResponseDTO.setTotalPage(page.getPages());
        userListResponseDTO.setTotalCount(page.getTotal());
        userListResponseDTO.setData(page.getRecords());
        return userListResponseDTO;
    }

    /**
     * 平台保存个人信息
     *
     * @param userId
     * @param userDetailSaveDTO
     * @return
     */
    @Override
    public Long saveByPlatform(Long userId, UserDetailSaveDTO userDetailSaveDTO) {
        User user = userMapper.selectById(userDetailSaveDTO.getId());
        if (user == null || !user.getSysType().equals(PlatformEnum.USER.getCode())) {
            throw new BusinessException(BizExceptionEnum.USER_NOT_EXISTED);
        }
        UserDetail userDetail = null;
        if (user.getCompanyId() == null) {
            return createuser(user,userDetailSaveDTO);
        } else {
            userDetail = userDetailMapper.selectById(user.getCompanyId());
            if(userDetail==null){
                return createuser(user,userDetailSaveDTO);
            }
            UserDetail userDetailTemp = new UserDetail();
            userDetailTemp = JSONObject.parseObject(JSONObject.toJSONString(userDetailSaveDTO), UserDetail.class);
            userDetailTemp.setId(userDetail.getId());
            userDetailTemp.setUpdateUser(userId);
            userDetailTemp.setUpdateTime(LocalDateTime.now());
            userDetailTemp.updateById();
            return userDetailTemp.getId();
        }

    }

    @Override
    public Long createUserDetail() {
        UserDetail  userDetail = new UserDetail();
        userDetail.setJobStatus(JobStatusEnum.FINDING.getType());
        userDetailMapper.insert(userDetail);
        return userDetail.getId();
    }


}
